package dao

import (
	"errors"
	"fmt"
	"laohuo/model"
)

func FetchSku(page, pagesize uint) ([]*model.SKU, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	rows, err := db.Query("SELECT * FROM `sku` WHERE isdel=0 ORDER BY `time` DESC LIMIT ?,?", (page-1)*pagesize, pagesize)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	defer rows.Close()

	var skus []*model.SKU
	for rows.Next() {
		var s model.SKU
		var isdel uint8
		var ext string
		if err := rows.Scan(&s.Id, &s.Name, &s.WareId, &s.Brand, &s.Material, &s.Specs, &s.Color, &ext, &s.Desc, &s.Time, &isdel); err != nil {
			continue
		}
		skus = append(skus, &s)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("数据解析失败: %v", err)
	}
	return skus, nil
}

func FetchSkuById(id uint) (*model.SKU, error) {
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	var s = &model.SKU{}
	var isdel uint8
	var ext string
	err = db.QueryRow("SELECT * FROM `sku` WHERE `id`=? and `isdel`=0", id).Scan(&s.Id, &s.Name, &s.WareId,
		&s.Brand, &s.Material, &s.Specs, &s.Color, &ext, &s.Desc, &s.Time, &isdel)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}

	return s, nil
}

func FetchBatchSkuById(ids []uint) ([]*model.SKU, error) {
	if len(ids) == 0 {
		return nil, errors.New("参数错误")
	}
	db, err := connect()
	if err != nil {
		return nil, err
	}
	defer db.Close()

	var in = make([]rune, 0, 2*len(ids))
	var params = make([]interface{}, 0, len(ids))
	for i := 0; i < len(ids); i++ {
		in = append(in, '?', ',')
		params = append(params, ids[i])
	}
	var placeholder = string(in[0 : len(in)-1])

	rows, err := db.Query(fmt.Sprintf("SELECT * FROM `sku` WHERE id in (%s) and isdel=0", placeholder), params...)
	if err != nil {
		return nil, fmt.Errorf("查询失败: %v", err)
	}
	defer rows.Close()

	var skus []*model.SKU
	for rows.Next() {
		var s model.SKU
		var isdel uint8
		var ext string
		if err := rows.Scan(&s.Id, &s.Name, &s.WareId, &s.Brand, &s.Material, &s.Specs, &s.Color, &ext, &s.Desc, &s.Time, &isdel); err != nil {
			continue
		}
		skus = append(skus, &s)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("供应商数据解析失败: %v", err)
	}
	return skus, nil
}

func AddSKU(sku *model.SKU) error {
	db, err := connect()
	if err != nil {
		return err
	}
	defer db.Close()

	res, err := db.Exec("INSERT INTO `sku`(`name`, `wareId`, `brand`, `material`, `specs`, `color`, `ext`, `desc`, `time`) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
		sku.Name, sku.WareId, sku.Brand, sku.Material, sku.Specs, sku.Color, sku.EncodeExt(), sku.Desc, sku.Time)
	if err != nil {
		return err
	}

	id, _ := res.LastInsertId()
	sku.Id = uint(id)
	return nil
}

func CountSku() (int, error) {
	db, err := connect()
	if err != nil {
		return 0, err
	}
	defer db.Close()

	var total int
	if err := db.QueryRow("SELECT COUNT(*) FROM `sku` WHERE `isdel`=0").Scan(&total); err != nil {
		return 0, err
	}
	return total, nil
}
